<template>
  <div class="container" v-if="goods">
    <van-icon class="top-share" v-if="me&&me.invite_code" name="qr" @click="showShare"/>
    <swiper class="swiper" indicator-dots="true" autoplay="true" interval="5000" duration="1000">
      <block v-for="(image,index) in goods.images" :index="index" :key="index">
        <swiper-item>
          <image :src="image + '?imageView2/1/w/640/h/640/q/90'" class="slide-image" mode="aspectFill" />
        </swiper-item>
      </block>
    </swiper>
    <div class="base-info">
      <div class="title">{{goods.title}}</div>
      <p class="price">￥{{ goodsPrice }}</p>
      <div class="others">
        <van-tag v-if="goods.is_proprietary" size="medium" color="#f2826a" plain style="margin-right:15px;" >自营商品</van-tag>
        <span class="cost">运费：{{ goods.express_fee}}</span>
        <span>剩余：{{ goods.inventory }}</span>
      </div>
    </div>
    <div class="brand-enter" v-if="goods.brand_id"  @click="onBrandEnter(goods.brand_id)">
      <van-row v-if="goods.brand">
        <van-col span="14" >
          <image class="brand-logo" :src="goods.brand.logo"/>
          <span class="brand-title">
            {{goods.brand.name}}
          </span>
        </van-col>
        <van-col span="10">
          <div class="brand-info">
            共有商品<span>{{goods.brand.count}}</span>件
            <span>
              <van-icon name="arrow" color="#E35E90" />
            </span>
          </div>
        </van-col>
      </van-row>
    </div>
    <div v-if="goods.product_detail_template">
      <rich-text :nodes="goods.product_detail_template.header"></rich-text>
    </div>
    <div class="info" v-if="goods.info&&goods.info.length>0">
      <div class="head">商品信息</div>
      <div class="item" v-for="(item,index) in goods.info" :index="index" :key="index">
        <span class="name">{{item.n}}</span>
        <span class="value">{{item.v}}</span>
      </div>
    </div>
    <rich-text :nodes="goods.content"></rich-text>
    <div v-if="goods.product_detail_template">
      <rich-text :nodes="goods.product_detail_template.footer"></rich-text>
    </div>
    <van-goods-action custom-class="mk-goods-action">
      <van-goods-action-icon icon="shop" text="首页" @click="goToHome" />
      <van-goods-action-icon icon="chat" text="客服" open-type="contact" :session-from="userMsg"  @contact="handleContact"/>
      <van-goods-action-icon icon="cart" text="购物车" :info="carAmount" @click="gotoCart" />
      <van-goods-action-button plain type="warning" text="加入购物车" @click="handleBuyStatus(2)" />
      <van-goods-action-button text="立即购买" @click="handleBuyStatus(1)" />
    </van-goods-action>
    <!-- 弹出sku设置 -->
    <van-popup :show="showSku" position="bottom" @click-overlay="handleBuyStatus">
      <div class="sku-box">
        <div class="header">
          <block v-if="goods.images">
            <img :src="goods.images[0]" />
          </block>
          <div class="info">
            <van-icon name="close" class="sku-close" @click="handleBuyStatus" />
            <p class="title">{{goods.title}}</p>
            <p class="price">￥{{price}}</p>
          </div>
        </div>
        <div class="sku" v-for="(item, index) in skuList.tree" :key="index" :index="index">
          <p>{{item.k}}</p>
          <span :class="{active: sitem.selected}" v-for="(sitem, skuindex) in item.v" :key="skuindex" @click="addSku(sitem, skuindex, index, item.v)">{{sitem.name}}</span>
        </div>
        <div class="count">
          <div class="left">
            购买数量:
            <p>剩余量: {{stockNumber}}</p>
          </div>
          <div class="right">
            <van-stepper :value="amount" integer min="1" step="1" @change="proCount" />
          </div>
        </div>
        <div class="footer">
          <van-goods-action custom-class="mk-goods-action">
            <van-goods-action-button v-if="!buyStatus" text="加入购物车" @click="addCart" />
            <van-goods-action-button v-if="buyStatus" text="立即购买" @click="purchase" :loading="payBtnStatus" />
          </van-goods-action>
        </div>
      </div>
    </van-popup>
    <van-toast id="van-toast"/>
    <van-dialog id="van-dialog" />
    <!-- 弹出sku设置结束 -->
  </div>
</template>
<script>
import * as CartAction from '@/api/cart'
import * as OrderAction from '@/api/order'
import pageFooter from '@/components/page-footer.vue'
import Dialog from 'vant-weapp/dist/dialog/dialog'
import Toast from 'vant-weapp/dist/toast/toast'
import env from '@/env'
import {mapState} from 'vuex'
import _ from 'lodash'
export default {
  props: ['goods'],
  data () {
    return {
      showSku: false,
      setSku: false,
      buyStatus: false,
      stockNumber: null,
      amount: 1,
      sku_id: '',
      skuList: [],
      selectedList: [],
      carAmount: null,
      price: null,
      payBtnStatus: false,
      userMsg: ''
    }
  },
  components: {
    pageFooter
  },
  computed: {
    ...mapState(['me']),
    ...mapState(['productInfo']),
    goodsPrice () {
      if (!this.goods) return
      if (this.goods.price * 1 === this.goods.max_price * 1) {
        return this.goods.price.toFixed(2)
      }
      return this.goods.price.toFixed(2) + '~' + this.goods.max_price.toFixed(2)
    }
  },
  onShow () {
    this.showSku = false
  },
  onLoad () {
    if (this.me) {
      this.userMsg = {
        nickName: this.me.nickname,
        avatarUrl: this.me.avatar
      }
      this.userMsg = JSON.stringify(this.userMsg)
    } else {
      this.getWxInfo()
    }
  },
  beforeMount () {
    this.selectedList.length = 0
    this.fetchCartItems()
    this.transProductInfo()
  },
  methods: {
    goToHome () {
      wx.switchTab({ url: '../home/index' })
    },
    onBrandEnter (id) {
      wx.navigateTo({ url: '../brand/index?id=' + id })
    },
    showShare () {
      wx.previewImage({
        urls: [env.API_HOST + '/image-render/mp-goods-invite-qr?pid=' + this.goods.id + '&c=' + this.me.invite_code]
      })
    },
    handleContact (e) {
      let path = e.mp.detail.path
      let query = e.mp.detail.query
      let params = ''
      if (path && query) {
        for (let key in query) {
          params = params + key + '=' + query[key] + '&'
        }
        params = params.slice(0, params.length - 1)
      } else return false
      wx.navigateTo({ url: path + '?' + params })
    },
    getWxInfo () {
      let that = this
      wx.getUserInfo({
        lang: 'zh_CN',
        success: function (res) {
          that.userInfo = res.userInfo
          that.userMsg = {
            nickName: res.userInfo.nickName,
            avatarUrl: res.userInfo.avatarUrl
          }
          that.userMsg = JSON.stringify(that.userMsg)
        },
        fail: console.error
      })
    },
    handleBuyStatus (tag) {
      this.showSku = !this.showSku
      if (tag) {
        if (tag === 1) this.buyStatus = true
        else { this.buyStatus = false }
      }
    },
    purchase () {
      if (!this.stockNumber) {
        Toast('当前库存不足，请选择其他型号')
        return
      }
      if (!this.amount) {
        Toast('请选择商品数量')
        return
      }
      if (!this.setSku) {
        Toast('请选择商品规格')
        return
      }
      this.payBtnStatus = true
      this.sendOrder()
    },
    gotoCart () {
      wx.switchTab({ url: '../cart/index' })
    },
    proCount (e) {
      this.amount = e.mp.detail
    },
    goAuth (err) {
      if (err.code * 1 === 4003) {
        Dialog.confirm({
          title: '美控家',
          message: '您还没有登录，是否现在前往登录'
        }).then(() => {
          wx.redirectTo({
            url: '../auth/login-index?target=goods&&id=' + this.goods.id
          })
        }).catch(() => {})
      } else {
        Toast.loading({
          duration: 0,
          mask: true,
          forbidClick: true,
          message: err.msg
        })
      }
    },
    addCart () {
      if (!this.stockNumber) {
        Toast('当前库存不足，请选择其他型号')
        return
      }
      if (!this.setSku) {
        Toast('请选择商品规格')
        return
      }
      let params = {
        amount: this.amount,
        sku_id: this.sku_id,
        goods_id: this.productInfo.id
      }
      CartAction.store(params)
        .then(() => {
          Toast.success('添加成功')
          this.showSku = !this.showSku
          this.carAmount = this.carAmount ? this.carAmount + 1 : 1
        }).catch(err => {
          this.goAuth(err)
        })
    },
    addSku (item, sindex, index, vlist) {
      vlist.forEach(pointer => { pointer.selected = false })
      item.selected = true
      let ks = this.skuList.tree[index].k_s
      let data = {
        [ks]: String(item.id)
      }
      let f = null
      this.selectedList.map(val => {
        for (let key in val) {
          if (key === ks) {
            val[key] = String(item.id)
            f = true
          }
        }
      })
      if (!f) this.selectedList.push(data)
      if (index <= this.skuList.tree.length - 1) this.skuSelected(ks, item.id)
      if (this.skuList.tree.length === this.selectedList.length) {
        this.setSku = true
      }
    },
    skuSelected (ks, id) {
      let filter = null
      let condition = {}
      this.selectedList.forEach((val) => {
        condition = _.assign(condition, val)
      })
      filter = _.find(this.skuList.list, condition)
      if (filter) {
        this.stockNumber = filter.stock_num
        if (filter.stock_num * 1 === 0) {
          this.amount = 0
        } else {
          this.amount = 1
        }
        this.price = (filter.price * 0.01).toFixed(2)
        this.sku_id = filter.id
      }
    },
    transProductInfo () {
      this.$store.commit('set_product_info', this.goods)
      if (this.goods) {
        this.skuList = this.goods.sku
        this.stockNumber = this.goods.inventory
        this.amount = 1
        this.price = this.goodsPrice
      }
    },
    // 发起订单
    sendOrder () {
      let params = {
        amount: this.amount,
        sku_id: this.sku_id,
        goods_id: this.productInfo.id
      }
      OrderAction.store(params)
        .then(res => {
          this.payBtnStatus = false
          wx.navigateTo({
            url: '../order/confirm?id=' + res.id
          })
        })
        .catch(err => {
          this.payBtnStatus = false
          this.goAuth(err)
        })
    },
    // 统计购物车数量
    fetchCartItems () {
      CartAction.list()
        .then(data => {
          this.carAmount = data.length
        })
        .catch(err => console.log(err))
    }
  }
}
</script>
<style lang="less" scoped>
@theme-red: #E6648C;

.container {
  position: relative;
  background: #f8f8f8;
  width: 100%;
  height: 100%;
  padding-bottom: 85rpx;
  .top-share {
    position:absolute;
    z-index:100;
    right:10rpx;
    top:10rpx;
    color: #333333;
    font-size:46rpx;
  }
  .swiper {
    border-radius: 25rpx;
    height: 750rpx;
    image {
      width: 100%;
      height: 750rpx;
    }
  }
  .base-info {
    background: #fff;
    padding: 15px;
    .title {
      font-size: 15px;
    }
    .price {
      font-size: 16px;
      color: @theme-red;
      margin: 10rpx 0;
    }
    .others {
      color: #999;
      font-size: 24rpx;
      .cost {
        margin-right: 40rpx;
      }
    }
  }
  .brand-enter {
    margin-top: 25rpx;
    padding: 10px 15px;
    background: #fff;
    .brand-logo {
      width:100rpx;
      height:100rpx;
      border-radius:50%;
    }
    .brand-title {
      padding:20rpx;
      position:relative;
      top:-34rpx;
      font-size:30rpx;
      font-weight: 300;
    }
    .brand-info {
      color:#9D9D9E;
      padding:32rpx;
      font-size:30rpx;
      padding-right:0;
      text-align:right;
      span {
        color: @theme-red;
      }
    }
  }
  .info {
    background: #fff;
    padding: 10px 15px;
    .head {
      font-size: 14px;
      padding: 0 15px 10px;
      margin: 0 -30rpx 20rpx;
      border-bottom: 1px solid #eee;
    }
    .item {
      margin-bottom: 5px;
      font-size: 24rpx;
      .name {
        width: 6em;
        display: inline-block;
        color: #666;
      }
      .value {
        color: #999;
      }
    }
  }
  .show-info {
    margin-top: 20rpx;
    image {
      width: 100%;
    }
  }
  .sku-box {
    padding: 10rpx;
    .header {
      position: relative;
      display: flex;
      flex-flow: row wrap;
      img {
        width: 160rpx;
        height: 160rpx;
      }
      .info {
        padding: 20rpx 40rpx;
        overflow: hidden;
        box-sizing: border-box;
        font-size: 28rpx;
        width: 78%;
        .sku-close {
          top: 10rpx;
          right: 30rpx;
          font-size: 40rpx;
          color: #999;
          position: absolute;
          text-align: center;
        }
        .title {
          font-size: 24rpx;
          padding-right: 45rpx;
          overflow: hidden;
        }
        .price {
          vertical-align: middle;
          color: @theme-red;
          font-size: 16px;
        }
      }
    }
    .sku {
      padding: 10rpx;
      border-top: 1rpx solid #f2f2f2;
      border-bottom: 1rpx solid #f2f2f2;
      p {
        padding-bottom: 10px;
        font-size: 14px;
      }
      span {
        display: inline-block;
        padding: 5px 9px;
        margin: 0 10px 10px 0;
        height: 28px;
        min-width: 52px;
        line-height: 16px;
        font-size: 12px;
        color: #333;
        text-align: center;
        border: 1px solid #999;
        border-radius: 4px;
        box-sizing: border-box;
      }
      span:link,
      span:hover,
      span:active,
      .active {
        color: #fff;
        border-color: @theme-red;
        background: @theme-red;
      }
    }
    .count {
      display: flex;
      flex-flow: row nowrap;
      box-sizing: border-box;
      .left {
        width: 50%;
        line-height: 30px;
        font-size: 30rpx;
        p {
          font-size: 26rpx;
          margin-right: 10px;
          color: #999;
        }
      }
      .right {
        width: 50%;
        padding: 10rpx 0 20rpx 110rpx;
      }
    }
    .footer {
      height: 100rpx;
    }
  }
}
</style>

